<template>
  <view class="container">
    <view class="form-container">
      <view class="form-header">
        <text class="form-title">问题反馈</text>
        <text class="form-subtitle">请详细描述您遇到的问题，我们会及时处理</text>
      </view>
      
      <view class="form-content">
        <view class="form-item">
          <text class="form-label">村小组 <text class="required">*</text></text>
          <picker 
            class="form-picker" 
            :value="groupIndex" 
            :range="villageGroups"
            @change="onGroupChange"
          >
            <view class="picker-text">{{ formData.villageGroup || '请选择村小组' }}</view>
          </picker>
        </view>
        
        <view class="form-item">
          <text class="form-label">问题类型 <text class="required">*</text></text>
          <picker 
            class="form-picker" 
            :value="typeIndex" 
            :range="problemTypes"
            @change="onTypeChange"
          >
            <view class="picker-text">{{ formData.type || '请选择问题类型' }}</view>
          </picker>
        </view>
        
        <view class="form-item">
          <text class="form-label">问题描述 <text class="required">*</text></text>
          <textarea 
            class="form-textarea" 
            v-model="formData.description" 
            placeholder="请详细描述您遇到的问题，包括时间、地点、具体情况等"
            maxlength="500"
            :show-confirm-bar="false"
          />
          <text class="char-count">{{ formData.description.length }}/500</text>
        </view>
        
        <view class="form-item">
          <text class="form-label">上传图片</text>
          <view class="image-upload">
            <view 
              class="image-item" 
              v-for="(image, index) in formData.images" 
              :key="index"
            >
              <image :src="getImageUrl(image)" class="uploaded-image" mode="aspectFill" />
              <view class="delete-btn" @tap="deleteImage(index)">
                <text class="delete-text">×</text>
              </view>
            </view>
            <view class="upload-btn" @tap="chooseImage" v-if="formData.images.length < 3">
              <text class="upload-text">+</text>
            </view>
          </view>
          <text class="upload-tip">最多上传3张图片</text>
        </view>
      </view>
      
      <view class="form-actions">
        <button class="submit-btn" @tap="submitForm" :disabled="!canSubmit">
          <text class="submit-text">{{ getSubmitButtonText() }}</text>
        </button>
        <view class="form-tips" v-if="!canSubmit">
          <text class="tips-text">{{ getValidationTips() }}</text>
        </view>
      </view>
    </view>
  </view>
</template>

<script>
import { feedbackApi, uploadApi, commonApi, utils } from '@/utils/api-simple.js'
import authService from '@/utils/auth.js'

export default {
  data() {
    return {
      typeIndex: -1,
      groupIndex: -1,
      problemTypes: ['基础设施', '环境卫生', '公共安全', '民生服务', '其他'],
      villageGroups: ['刘家湾组', '陈家湾组', '杜家冲组', '五坝组', '长房组', '大坪子组'],
      formData: {
        villageGroup: '',
        type: '',
        description: '',
        images: []
      },
      uploading: false,
      userInfo: null
    }
  },
  computed: {
    canSubmit() {
      return this.formData.villageGroup && 
             this.formData.type && 
             this.formData.description &&
             !this.uploading
    }
  },
  onLoad() {
    this.checkAuthAndLoad()
  },
  methods: {
    // 检查认证并加载数据
    async checkAuthAndLoad() {
      try {
        // 检查是否已登录
        if (!authService.isLoggedIn()) {
          uni.showToast({
            title: '请先登录',
            icon: 'none'
          })
          setTimeout(() => {
            uni.redirectTo({
              url: '/pages/login/login'
            })
          }, 1500)
          return
        }
        
        // 获取用户信息
        this.userInfo = authService.getUserInfo()
        console.log('当前用户信息:', this.userInfo)
        
        // 加载问题类型
        this.loadProblemTypes()
      } catch (error) {
        console.error('认证失败:', error)
        uni.showToast({
          title: '登录失败，请重试',
          icon: 'none'
        })
      }
    },
    
    // 加载问题类型
    async loadProblemTypes() {
      try {
        console.log('开始加载问题类型...')
        const response = await commonApi.getProblemTypes()
        console.log('问题类型响应:', response)
        
        if (response.code === 200 && response.data) {
          this.problemTypes = response.data
          console.log('问题类型加载成功:', this.problemTypes)
        } else {
          console.warn('问题类型响应异常:', response)
          // 保持默认值
        }
      } catch (error) {
        console.error('加载问题类型失败:', error)
        // 保持默认值，不影响用户使用
      }
    },
    
    // 选择村小组
    onGroupChange(e) {
      this.groupIndex = e.detail.value
      this.formData.villageGroup = this.villageGroups[e.detail.value]
    },
    
    // 选择问题类型
    onTypeChange(e) {
      this.typeIndex = e.detail.value
      this.formData.type = this.problemTypes[e.detail.value]
    },
    
    // 选择图片
    chooseImage() {
      const remainingCount = 3 - this.formData.images.length
      if (remainingCount <= 0) {
        uni.showToast({
          title: '最多只能上传3张图片',
          icon: 'none'
        })
        return
      }
      
      uni.chooseImage({
        count: remainingCount,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          this.uploadImages(res.tempFilePaths)
        }
      })
    },
    
    // 上传图片
    async uploadImages(filePaths) {
      if (this.uploading) {
        uni.showToast({
          title: '正在上传中，请稍候',
          icon: 'none'
        })
        return
      }
      
      this.uploading = true
      
      try {
        console.log('开始上传图片，文件数量:', filePaths.length)
        
        const uploadPromises = filePaths.map(filePath => uploadApi.uploadImage(filePath))
        const results = await Promise.all(uploadPromises)
        
        console.log('上传结果:', results)
        
        const uploadedUrls = results.map((result, index) => {
          // 检查返回结果的结构 - 根据实际API返回格式
          if (result && result.url) {
            console.log(`图片${index + 1}上传成功:`, result.url)
            return result.url
          } else if (result && result.data && result.data.url) {
            console.log(`图片${index + 1}上传成功(嵌套格式):`, result.data.url)
            return result.data.url
          } else {
            console.error(`图片${index + 1}上传结果格式异常:`, result)
            return null
          }
        }).filter(url => url !== null)
        
        if (uploadedUrls.length > 0) {
          this.formData.images = [...this.formData.images, ...uploadedUrls]
          uni.showToast({
            title: `成功上传${uploadedUrls.length}张图片`,
            icon: 'success'
          })
        } else {
          uni.showToast({
            title: '图片上传失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('图片上传失败:', error)
        uni.showToast({
          title: '图片上传失败: ' + (error.message || '未知错误'),
          icon: 'none'
        })
      } finally {
        this.uploading = false
      }
    },
    
    // 删除图片
    async deleteImage(index) {
      const imageUrl = this.formData.images[index]
      
      try {
        // 如果是已上传的图片，先删除服务器上的文件
        if (imageUrl && !imageUrl.includes('temp')) {
          await uploadApi.deleteImage(imageUrl)
        }
        
        this.formData.images.splice(index, 1)
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
      } catch (error) {
        console.error('删除图片失败:', error)
        // 即使删除失败，也从列表中移除
        this.formData.images.splice(index, 1)
        uni.showToast({
          title: '删除成功',
          icon: 'success'
        })
      }
    },
    
    // 提交表单
    async submitForm() {
      console.log('点击提交按钮')
      console.log('canSubmit:', this.canSubmit)
      console.log('formData:', this.formData)
      console.log('userInfo:', this.userInfo)
      
      if (!this.canSubmit) {
        const tips = this.getValidationTips()
        uni.showToast({
          title: tips,
          icon: 'none',
          duration: 3000
        })
        return
      }
      
      if (!this.userInfo) {
        uni.showToast({
          title: '用户信息获取失败，请重新登录',
          icon: 'none'
        })
        return
      }
      
      uni.showLoading({
        title: '提交中...'
      })
      
      try {
        const submitData = {
          userId: this.userInfo.userId,
          name: this.userInfo.wechatNickname || this.userInfo.nickName || '微信用户',
          phone: '', // 不再收集手机号
          villageGroup: this.formData.villageGroup,
          type: this.formData.type,
          description: this.formData.description,
          images: this.formData.images
        }
        
        const response = await feedbackApi.submitFeedback(submitData)
        console.log('提交反馈响应:', response)
        
        if (response.code === 200) {
          uni.hideLoading()
          
          // 尽可能多地兼容后端返回的编号字段或消息中的编号
          const data = response.data || {}
          const msgText = (response.message || response.msg || '').toString()
          const tryKeys = ['serial', 'serialNo', 'serialNumber', 'feedbackNo', 'feedbackCode', 'orderNo', 'code', 'id']
          let serial = '未知'
          // 先从 data 中取
          for (const k of tryKeys) {
            if (data && data[k]) { serial = data[k]; break }
          }
          // 再从响应顶层取（后端把 serial 放在根上的情况）
          if (serial === '未知') {
            for (const k of tryKeys) {
              if (response && response[k]) { serial = response[k]; break }
            }
          }
          if (serial === '未知' && msgText) {
            const match = msgText.match(/(FK\d{6,})/i)
            if (match && match[1]) serial = match[1]
          }
          const message = response.message || response.msg || '提交成功'
          
          uni.showModal({
            title: '提交成功',
            content: `您的问题已成功提交，反馈编号：${serial}，我们会尽快处理并反馈结果。`,
            showCancel: false,
            success: () => {
              // 通知反馈列表页面刷新数据
              console.log('发送刷新反馈列表事件')
              uni.$emit('refreshFeedbackList')
              console.log('刷新事件已发送')
              
              // 延迟返回，确保事件有时间传递
              setTimeout(() => {
                // 使用页面参数方式传递刷新信号
                uni.navigateBack({
                  success: () => {
                    console.log('已返回反馈列表页面')
                    // 再次发送事件作为备选方案
                    setTimeout(() => {
                      uni.$emit('refreshFeedbackList')
                      console.log('备选刷新事件已发送')
                    }, 200)
                  }
                })
              }, 100)
            }
          })
        } else {
          uni.hideLoading()
          uni.showToast({
            title: response.message || response.msg || '提交失败',
            icon: 'none'
          })
        }
      } catch (error) {
        console.error('提交反馈失败:', error)
        uni.hideLoading()
        uni.showToast({
          title: '提交失败，请重试',
          icon: 'none'
        })
      }
    },
    
    // 获取图片URL
    getImageUrl(image) {
      return utils.getImageUrl(image)
    },
    
    // 获取提交按钮文本
    getSubmitButtonText() {
      if (this.uploading) {
        return '提交中...'
      }
      if (!this.canSubmit) {
        return '请完善必填信息'
      }
      return '提交反馈'
    },
    
    // 获取验证提示
    getValidationTips() {
      const tips = []
      if (!this.formData.villageGroup) {
        tips.push('请选择村小组')
      }
      if (!this.formData.type) {
        tips.push('请选择问题类型')
      }
      if (!this.formData.description) {
        tips.push('请填写问题描述')
      }
      if (this.uploading) {
        tips.push('正在上传图片，请稍候')
      }
      return tips.join('、')
    }
  }
}
</script>

<style scoped>
.container {
  padding: 20rpx;
  background-color: #f5f5f5;
  min-height: 100vh;
}

.form-container {
  background-color: white;
  border-radius: 12rpx;
  padding: 30rpx;
}

.form-header {
  text-align: center;
  margin-bottom: 40rpx;
  padding-bottom: 30rpx;
  border-bottom: 2rpx solid #f0f0f0;
}

.form-title {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  color: #4CAF50;
  margin-bottom: 10rpx;
}

.form-subtitle {
  display: block;
  font-size: 26rpx;
  color: #666;
}

.form-content {
  
}

.form-item {
  margin-bottom: 30rpx;
}

.form-label {
  display: block;
  font-size: 28rpx;
  color: #333;
  font-weight: bold;
  margin-bottom: 15rpx;
}

.required {
  color: #ff4444;
}

.form-input, .form-textarea {
  width: 100%;
  padding: 20rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 8rpx;
  font-size: 28rpx;
  color: #333;
  background-color: #fafafa;
}

.form-input:focus, .form-textarea:focus {
  border-color: #4CAF50;
  background-color: white;
}

.form-picker {
  width: 100%;
  padding: 20rpx;
  border: 2rpx solid #e0e0e0;
  border-radius: 8rpx;
  background-color: #fafafa;
}

.picker-text {
  font-size: 28rpx;
  color: #333;
}

.form-textarea {
  height: 200rpx;
  resize: none;
}

.char-count {
  display: block;
  text-align: right;
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

.image-upload {
  display: flex;
  flex-wrap: wrap;
  gap: 15rpx;
}

.image-item {
  position: relative;
  width: 150rpx;
  height: 150rpx;
}

.uploaded-image {
  width: 100%;
  height: 100%;
  border-radius: 8rpx;
}

.delete-btn {
  position: absolute;
  top: -10rpx;
  right: -10rpx;
  width: 40rpx;
  height: 40rpx;
  background-color: #ff4444;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.delete-text {
  color: white;
  font-size: 24rpx;
  font-weight: bold;
}

.upload-btn {
  width: 150rpx;
  height: 150rpx;
  border: 2rpx dashed #ccc;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fafafa;
}

.upload-text {
  font-size: 48rpx;
  color: #999;
}

.upload-tip {
  display: block;
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

.form-actions {
  margin-top: 40rpx;
}

.submit-btn {
  width: 100%;
  background: linear-gradient(135deg, #4CAF50, #45a049);
  color: white;
  border: none;
  border-radius: 12rpx;
  padding: 24rpx;
  font-size: 32rpx;
  font-weight: bold;
}

.submit-btn:disabled {
  background: #ccc;
}

.submit-text {
  color: white;
}

.form-tips {
  margin-top: 20rpx;
  text-align: center;
}

.tips-text {
  font-size: 24rpx;
  color: #ff6b6b;
  background-color: #fff5f5;
  padding: 10rpx 20rpx;
  border-radius: 8rpx;
  border: 1rpx solid #ffebee;
}
</style>
